package com.bed.lovewithpatientbed.service.impl;

import com.bed.lovewithpatientbed.common.SoftDelStatus;
import com.bed.lovewithpatientbed.common.bean.LayUiPageBean;
import com.bed.lovewithpatientbed.common.params.OrderSearchParams;
import com.bed.lovewithpatientbed.dao.OrderDao;
import com.bed.lovewithpatientbed.dao.OrderTypeDao;
import com.bed.lovewithpatientbed.pojo.*;
import com.bed.lovewithpatientbed.service.DeptService;
import com.bed.lovewithpatientbed.service.HospitalService;
import com.bed.lovewithpatientbed.service.IOrderService;
import com.bed.lovewithpatientbed.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author xuxiaoding
 * @version 1.0.0
 * @ClassName OrderServiceImpl.java
 * @Description IOrderService 实现类
 */
@Service
public class OrderServiceImpl implements IOrderService{

    private OrderDao orderDao;

    private OrderTypeDao orderTypeDao;

    private HospitalService hospitalService;

    private DeptService deptService;

    @Autowired
    public void setOrderDao(OrderDao orderDao) {
        this.orderDao = orderDao;
    }

    @Autowired
    public void setOrderTypeDao(OrderTypeDao orderTypeDao) {
        this.orderTypeDao = orderTypeDao;
    }

    @Autowired
    public void setHospitalService(HospitalService hospitalService) {
        this.hospitalService = hospitalService;
    }

    @Autowired
    public void setDeptService(DeptService deptService) {
        this.deptService = deptService;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createOrder(Order order) {
        // 计算订单额度
        OrderType orderType = orderTypeDao.selectByPrimaryKey(order.getOrderTypeId());
        if (orderType == null) {
            return false;
        }
        order.setOrderPay(BigDecimal.valueOf(orderType.getOrderPrice() * order.getOrderUseTime()));

        // 设置订单开始时间
        order.setOrderStartTime(DateUtil.getCurrentDate());
        order.setSoftdel(SoftDelStatus.SOFT_DEL_EXIST);

        int effectedRow = orderDao.insert(order);

        return effectedRow == 1;
    }

    @Override
    public List<Order> retrieveOrderByUserId(Integer userId) {
        // 断言
        assert userId != null && userId > 0;

        OrderExample orderExample = new OrderExample();
        orderExample.setOrderByClause("order_start_time desc");
        orderExample.createCriteria().andUserIdEqualTo(userId);

        return orderDao.selectByExample(orderExample);
    }

    @Override
    public long getOrderCountByUserId(Integer userId) {
        OrderExample orderExample = new OrderExample();
        orderExample.createCriteria().andUserIdEqualTo(userId);
        return orderDao.countByExample(orderExample);
    }

    @Override
    public BigDecimal getOrderTotalPayByUserId(Integer userId) {
        return orderDao.selectOrderTotalPayByUserId(userId);
    }

    /**
     * @description 日期区间查询某医院的订单额
     * @author tyl
     * @updateTime 2020/10/15 15:11
     */
    @Override
    public List<Order> selecOrderNumByHospitalId(String start, String end, Integer hospitalId) throws ParseException {
        /*转换日期格式*/
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date dateStart = null;
        Date dateEnd = null;
        if(start!=null&&!"".equals(start)&&end!=null&&!"".equals(end)) {
             dateStart = format.parse(start);
             dateEnd = format.parse(end);
        }
        /*添加查询条件*/
        OrderExample example = new OrderExample();
        OrderExample.Criteria criteria = example.createCriteria();
        /*添加日期查询条件*/
        if(dateStart!=null&&!"".equals(dateStart)&&dateEnd!=null&&!"".equals(dateEnd)) {
            criteria.andOrderStartTimeBetween(dateStart, dateEnd);
        }
        /*添加医院id*/
        if(hospitalId!=null&&!"".equals(hospitalId)) {
            criteria.andHospitalIdEqualTo(hospitalId);
        }
//        /*得到日期区间内某医院的订单数*/
//        long l = orderDao.countByExample(example);
        /*得到日期区间内某个医院的所有订单*/
        List<Order> orderList = orderDao.selectByExample(example);
        /*遍历订单集合，查询某一天的订单数量*/
        return orderList;
    }

    @Override
    public List<Order> retrieveOrderByConditionWithLimit(LayUiPageBean pageBean, OrderSearchParams orderSearchParams) {
        OrderExample orderExample = new OrderExample();
        // 添加分页
        if (pageBean != null && pageBean.getPage() > 0 && pageBean.getLimit() > 0) {
            orderExample.setOffset((pageBean.getPage() - 1) * pageBean.getLimit());
            orderExample.setLimit(pageBean.getLimit().intValue());
        }
        // 追加条件
        appendCriteria(orderSearchParams, orderExample.createCriteria());
        // 按订单时间倒序排序
        orderExample.setOrderByClause("order_start_time desc");

        return orderDao.selectByExample(orderExample);
    }

    @Override
    public List<Hospital> retrieveAllHospital() {
        return hospitalService.getAll();
    }

    @Override
    public long getCountByCondition(OrderSearchParams orderSearchParams) {
        return 0;
    }

    @Override
    public List<Dept> retrieveDeptListByHospitalId(Integer hospitalId) {
        // 偷懒了，没有 hospital_dept 中间表
        return deptService.getAll();
    }

    @Override
    public List<OrderType> retrieveAllOrderType() {
        return orderTypeDao.selectByExample(null);
    }

    /**
     * @title appendCriteria
     * @description 根据 orderSearchParams 在 OrderExample 中追加条件
     * @author xuxiaoding
     * @param orderSearchParams 搜索条件
     * @param criteria OrderExample.Criteria
     */
    private void appendCriteria(OrderSearchParams orderSearchParams, OrderExample.Criteria criteria) {
        if (criteria != null) {
            // 查询未被删除的状态
            criteria.andSoftdelEqualTo(SoftDelStatus.SOFT_DEL_EXIST);
            // 追加条件
            if (orderSearchParams != null) {
                // 要求订单编号模糊查询，但是只有orderId，并没有订单编号，无法做主键的模糊查询，所以这里直接查询
                if (orderSearchParams.getOrderId() != null && orderSearchParams.getOrderId() > 0) {
                    criteria.andOrderIdEqualTo(orderSearchParams.getOrderId());
                }
                if (orderSearchParams.getHospitalId() != null && orderSearchParams.getHospitalId() > 0) {
                    criteria.andHospitalIdEqualTo(orderSearchParams.getHospitalId());
                }
                if (orderSearchParams.getDeptId() != null && orderSearchParams.getDeptId() > 0) {
                    criteria.andDeptIdEqualTo(orderSearchParams.getDeptId());
                }
                if (orderSearchParams.getOrderTypeId() != null && orderSearchParams.getOrderTypeId() > 0) {
                    criteria.andOrderTypeIdEqualTo(orderSearchParams.getOrderTypeId());
                }
                if (orderSearchParams.getOrderStartFromTime() != null
                        && orderSearchParams.getOrderStartToTime() != null) {
                    criteria.andOrderStartTimeBetween(orderSearchParams.getOrderStartFromTime(),
                            orderSearchParams.getOrderStartToTime());
                }
            }
        }
    }


}
